package com.todaynews.frame.okhttp;

import com.todaynews.frame.common.CommonConfig;
import com.todaynews.frame.logger.Logger;
import com.todaynews.utils.NetworkUtils;
import com.todaynews.utils.file.FileUtils;
import java.io.File;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Dispatcher;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by jack
 */

public class OkHttpUtils {

    private static OkHttpUtils okHttpUtils;
    private OkHttpClient okHttpClient;

    private OkHttpUtils(){

        /*HttpsUtil.SSLParams sslParams = HttpsUtil.getSslSocketFactory(AppDroid.getInstance(),
                new int[0], R.raw.tomcat, "password");
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClient = okHttpClientBuilder
                .retryOnConnectionFailure(false)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return hostname.equals(session.getPeerHost());
                        //return true;
                    }
                }).build();*/

        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        /**增加头部信息的拦截器*/
        Interceptor headerInterceptor = chain -> {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547");
            builder.addHeader("Cache-Control", "max-age=0");
            builder.addHeader("Upgrade-Insecure-Requests", "1");
            builder.addHeader("X-Requested-With", "XMLHttpRequest");
            builder.addHeader("Cookie", "uuid=\"w:f2e0e469165542f8a3960f67cb354026\"; __tasessionId=4p6q77g6q1479458262778; csrftoken=7de2dd812d513441f85cf8272f015ce5; tt_webid=36385357187");
            return chain.proceed(builder.build());
        };
        okHttpClient = okHttpClientBuilder
                .addInterceptor(headerInterceptor)//添加头部信息拦截器
                .addInterceptor(logInterceptor)//添加log拦截器
                .cache(getCache())
                .connectTimeout(CommonConfig.CONNECTIONTIME, TimeUnit.SECONDS)//连接超时
                .readTimeout(CommonConfig.READTIME, TimeUnit.SECONDS)//读取超时
                .writeTimeout(CommonConfig.WRITETIME, TimeUnit.SECONDS)//写入超时
                .retryOnConnectionFailure(false)
                .build();
    }

    public static OkHttpUtils getInstance(){
        if(okHttpUtils == null){
            synchronized (OkHttpUtils.class){
                okHttpUtils = new OkHttpUtils();
            }
        }
        return  okHttpUtils;
    }

    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    public void cancel(Object tag) {
        if(okHttpClient != null){
            Dispatcher dispatcher = okHttpClient.dispatcher();
            for (Call call : dispatcher.queuedCalls()) {
                if (tag.equals(call.request().tag())) {
                    call.cancel();
                }
            }
        }
    }

    public void cancelAll(){
        if(okHttpClient != null){
            okHttpClient.dispatcher().cancelAll();
        }
    }

    /**请求访问quest和response拦截器*/
    private Interceptor logInterceptor = chain -> {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Logger.e("----------Request Start----------------");
        Logger.e("| " + request.toString());
        Logger.json("| Response:" + content);
        Logger.e("----------Request End:" + duration + "毫秒----------");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    };

    /**
     * okhttp缓存
     */
    private Cache getCache(){
        // 缓存目录
        File httpCacheDirectory = new File(FileUtils.getInstance().getRootDirectory(),CommonConfig.CACHE_SP_NAME);
        Cache cache = new Cache(httpCacheDirectory, CommonConfig.OKHTTP_CACHE_SIZE);
        return cache;
    }

    //缓存配置
    private Interceptor cacheInterceptor = chain -> {

        CacheControl.Builder cacheBuilder = new CacheControl.Builder();
        cacheBuilder.maxAge(0, TimeUnit.SECONDS);
        cacheBuilder.maxStale(365, TimeUnit.DAYS);
        CacheControl cacheControl = cacheBuilder.build();

        Request request = chain.request();
        if (!NetworkUtils.getInstance().isNetworkConnected()) {
            request = request.newBuilder()
                    .cacheControl(cacheControl)
                    .build();
        }
        Response originalResponse = chain.proceed(request);
        if (!NetworkUtils.getInstance().isNetworkConnected()) {
            int maxAge = 0; // read from cache
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public ,max-age=" + maxAge)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    };

}
